package com.sinochem.yunlian.ship.base.biz;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sinochem.yunlian.ship.base.constants.BsPortConstant;
import com.sinochem.yunlian.ship.base.entity.BsPort;
import com.sinochem.yunlian.ship.base.enume.BasePortLevel;
import com.sinochem.yunlian.ship.base.mapper.BsPortMapper;
import com.sinochem.yunlian.ship.base.vo.request.manage.ReqEditPortForm;
import com.sinochem.yunlian.ship.base.vo.request.manage.ReqFindPortListVo;
import com.sinochem.yunlian.ship.base.vo.response.MPortVo;
import com.sinochem.yunlian.ship.base.vo.response.PortVo;
import com.sinochem.yunlian.ship.common.biz.BaseBiz;
import com.sinochem.yunlian.ship.common.constant.DisableStatus;
import com.sinochem.yunlian.ship.common.exception.BaseException;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 港口信息表
 *
 * @author panyanan
 * @email  panyanan@ship.com
 * @date 2017-11-20 11:38:27
 */
@Service
public class BsPortBiz extends BaseBiz<BsPortMapper,BsPort> {

    private final Logger log = LoggerFactory.getLogger(BsMaterialCategoryBiz.class);

    public List<BsPort> findAllPorts() {
        return mapper.findAllPort();
    }

    public List<BsPort> findAllPortsByLevel(int disableStatus, int level) {
        return mapper.findAllPortByLevel(disableStatus, level);
    }
      
    public Page<BsPort> findPortByCondition(Map params){
       Page<BsPort>  result =PageHelper.startPage(Integer.parseInt(params.get("pageNum")+""),Integer.parseInt(params.get("pageSize")+""));
        mapper.findPortByCondition(params);
        return result;
    }

	public String getPortNameById(Long id) {
		HashMap<Object, Object> hashMap = new HashMap<>();
		hashMap.put("id", id);
		hashMap.put("status", DisableStatus.STATUS_ENABLE);

		return mapper.getPortNameByMap(hashMap);
	}

	/**
	 * @Auther: wanghui
	 * @Dscription: 运营港口管理
	 * @Date: Created in 15:11 2018/3/6
	 **/
	public List<BsPort> findAllPortsName(){
        return mapper.findAllPortName();
    }

    public List<BsPort> findCitysById(Long parentId){
	    return mapper.findCityById(parentId);
    }

    public List<BsPort> findPortListByMap(Map<String,Object> params){
        return mapper.findPortListByMap(params);
    }



    @Transactional(rollbackFor =  Exception.class)
    public void updatePort(Long id, Integer disableStatus, BsPort bsPort, int maxLevel) {
        BsPortBiz.HasDealing dealing = new BsPortBiz.HasDealing();
        try {
            updatePortDisableStatus(id, disableStatus, bsPort, maxLevel, dealing);
        }  catch (SQLException e) {
            log.error("操作失败了{}",e);
            throw BaseException.message("操作失败了");
        }

    }

    @Transactional(rollbackFor =  Exception.class)
    public void updatePortDisableStatus(Long id, Integer disableStatus, BsPort bsPort, int maxLevel, BsPortBiz.HasDealing dealing) throws SQLException{
        if (maxLevel == bsPort.getLevel()) {
            updatePortRootStatus(bsPort, disableStatus, dealing);
            // 叶子节点
            mapper.updatePortDisableStatus(id, disableStatus, null);
        } else {
            // 存在子节点,获取所有叶子节点
            List<BsPort> lists = mapper.selectPortList(bsPort.getId());
            updatePortRootStatus(bsPort, disableStatus, dealing);
            if (lists == null || lists.isEmpty()) {
                mapper.updatePortDisableStatus(id, disableStatus, null);
                return;
            }
            mapper.updatePortDisableStatus(id, disableStatus, null);
            for (BsPort bsPort1 : lists ){
                updatePortDisableStatus(bsPort1.getId(), disableStatus, bsPort1, maxLevel, dealing);
            }
        }
    }

    public void updatePortRootStatus(BsPort bsPort, Integer disableStatus, BsPortBiz.HasDealing dealing) {
        if (bsPort.getParentId() != 0 && DisableStatus.STATUS_ENABLE == disableStatus && !dealing.hasDealing) {
            // 不是根节点
            log.info("存在父节点，父节点的id为:{}", bsPort.getParentId());
            mapper.updatePortDisableStatus(bsPort.getParentId(), disableStatus, null);
            BsPort parentPort = this.selectPortById(bsPort.getParentId());
            if (parentPort != null) {
                updatePortRootStatus(parentPort, disableStatus, dealing);
            } else {
                dealing.hasDealing = true;
            }
        } else {
            dealing.hasDealing = true;
        }
    }

    //获取当前节点最大排序号
    public int selectPortMaxLevel(){
        return mapper.selectPortMaxLevel();
    }

    public PageInfo<BsPort> findCity(ReqFindPortListVo form){
        Map<String,Object> params = new HashMap<>();
        params.put("keyword",form.getKeyword());
        params.put("id",form.getId());
        PageHelper.startPage(form.getPageNum(),form.getPageSize());
        List<BsPort> list = mapper.findCity(params);
        return new PageInfo<>(list);
    }

    public PageInfo<BsPort> findAllPorts(ReqFindPortListVo form){
        Map<String,Object> params = new HashMap<>();
        params.put("keyword",form.getKeyword());
        params.put("id",form.getId());
        PageHelper.startPage(form.getPageNum(),form.getPageSize());
        List<BsPort> list = mapper.findAllPorts(params);
        return new PageInfo<>(list);
    }


    /**
     *
     * @Description: 根据id获取货品
     */
    public BsPort selectPortById(Long id) {
        return mapper.selectPortById(id);
    }

    /**
     * @Auther: wanghui
     * @Dscription: 根据id获取港口详情
     * @Date: Created in 17:56 2018/3/9
     **/
    public HashMap<Object, Object> selectPortDetail(Long id) {
        HashMap<Object,Object> hashMap = new HashMap<>();
        // 获取当前的货品信息
        BsPort bsPort = this.selectPortById(id);
        if (bsPort == null) {
            return null;
        }
        hashMap.put("id", bsPort.getId());
        hashMap.put("portName", bsPort.getPortName());
        hashMap.put("seqNum", bsPort.getSeqNum());
        if (bsPort.getLevel() == BasePortLevel.ONE_LEVEL.getLevel()) {
            hashMap.put("parentLevel", 0);
            hashMap.put("parentId", 0);
            hashMap.put("parentPortName", "根目录");
            // 设置根目录
            ArrayList<PortVo> lists = new ArrayList<>();
            PortVo vo = new PortVo();
            // 根目录赋值
            vo.setPortName("根目录");
            vo.setId(0L);

            lists.add(vo);
            hashMap.put("portLevel", lists);
        }
        // 获取父类货品信息
        BsPort parentPort = this.selectPortById(bsPort.getParentId());
        if (parentPort == null) {
            log.info("无父类信息:{}", parentPort);
            return hashMap;
        }
        hashMap.put("parentLevel", parentPort.getLevel());
        hashMap.put("parentId", parentPort.getId());
        hashMap.put("parentPortName", parentPort.getPortName());
        // 获取父节点的所有港口信息
        List<PortVo> parents = mapper.selectPortLevelList(parentPort.getLevel(), parentPort.getParentId());
        hashMap.put("portLevel", parents);
        return hashMap;
    }

    /**
     * @Auther: wangHui
     * @Dscription: 修改/添加港口
     * @Date: Created in 15:25 2018/3/12
     **/
    public void updateMaterial(ReqEditPortForm form) {
        if (form.getId() == null && form.getParentId() != null) {
            if (StringUtils.isEmpty(form.getPortName())) {
                throw BaseException.message("港口名称不能为空");
            }
            BsPort port =  new BsPort();

            // 判断是否是添加根目录下的一级节点
            if (form.getParentId() == 0) {
                // 获取当前节点最大编码
                String maxEnName = mapper.selectPortMaxEnName(0L);
                // 检查港口名称是否存在
                BsPort bsPort = mapper.selectPortByPortNameAndLevel(form.getPortName(), BasePortLevel.ONE_LEVEL.getLevel());
                if (bsPort != null) {
                    throw BaseException.message("流域名称:" + form.getPortName() + "已存在");
                }
                //获取当前节点最大排序号
                Integer maxSeqNum = mapper.selectPortMaxSeqNum(form.getParentId());
                // 添加流域
                port.setPortName(form.getPortName());
                port.setDisableStatus(DisableStatus.STATUS_ENABLE);
                //港口编码
                port.setEnName(getEnName(maxEnName,1,false,null));
                port.setLevel(BsPortConstant.LEVLE_1);
                port.setParentId(0L);
                port.setSeqNum(maxSeqNum + 1);
                mapper.insertSelective(port);
                return;
            }else if(form.getParentId() == 1) {
                // 判断要添加的港口是否存在
                BsPort bsPort = this.selectPortById(form.getParentId());
                if (bsPort == null) {
                    throw BaseException.message("不存在您选择的港口等级");
                }
                if (bsPort.getLevel() > 2) {
                    throw BaseException.message("您选择的港口等级超出范围");
                }
                // 获取当前节点最大编码
                String maxEnName = mapper.selectPortMaxEnName(bsPort.getId());
                boolean isOneLine = false;
                if (maxEnName =="" || maxEnName == null) {
                    maxEnName = mapper.selectPortMaxEnNameById(bsPort.getId());
                    isOneLine = true;
                }
                // 检查港口名称是否存在
                BsPort port1 = mapper.selectPortByPortNameAndLevel(form.getPortName(), BasePortLevel.TWO_LEVEL.getLevel());
                if (port1 != null) {
                    throw BaseException.message("城市名称:" + form.getPortName() + "已存在");
                }
                //获取当前节点最大排序号
                Integer maxSeqNum = mapper.selectPortMaxSeqNum(form.getParentId());
                // 添加城市
                port.setPortName(form.getPortName());
                port.setDisableStatus(DisableStatus.STATUS_ENABLE);
                port.setLon(form.getLon());
                port.setLat(form.getLat());
                port.setEnName(getEnName(maxEnName, 1, isOneLine, bsPort.getLevel() + 1));
                port.setLevel(bsPort.getLevel() + 1);
                port.setParentId(bsPort.getId());
                port.setSeqNum(maxSeqNum + 1);
                mapper.insertSelective(port);
            }else {
                // 判断要添加的港口是否存在
                BsPort bsPort = this.selectPortById(form.getParentId());
                if (bsPort == null) {
                    throw BaseException.message("不存在您选择的港口等级");
                }
                if (bsPort.getLevel() > 4) {
                    throw BaseException.message("您选择的港口等级超出范围");
                }
                // 获取当前节点最大编码
                String maxEnName = mapper.selectPortMaxEnName(bsPort.getId());
                boolean isOneLine = false;
                if (maxEnName == null) {
                    maxEnName = mapper.selectPortMaxEnNameById(bsPort.getId());
                    isOneLine = true;
                }
                // 检查港口名称是否存在
                BsPort bsPort1 = mapper.selectPortByPortNameAndLevel(form.getPortName(), bsPort.getLevel() + 1);
                if (bsPort1 != null) {
                    throw BaseException.message("港口名称:" + form.getPortName() + "已存在");
                }
                //获取当前节点最大排序号
                Integer maxSeqNum = mapper.selectPortMaxSeqNum(form.getParentId());
                // 添加港口
                port.setPortName(form.getPortName());
                port.setDisableStatus(DisableStatus.STATUS_ENABLE);
                port.setLon(form.getLon());
                port.setLat(form.getLat());
                port.setEnName(getEnName(maxEnName, 1, isOneLine, bsPort.getLevel() + 1));
                port.setLevel(bsPort.getLevel() + 1);
                port.setParentId(bsPort.getId());
                if(maxSeqNum != null){
                    port.setSeqNum(maxSeqNum + 1);
                }
                mapper.insertSelective(port);
            }
        } else {

            if (StringUtils.isEmpty(form.getPortName()) || form.getSeqNum() == null || form.getParentId() == null) {
                throw BaseException.message("更新数据不能为空");
            }
            BsPort parentPort = null;
            if (form.getParentId() != 0) {
                // 判断父节点是否存在
                parentPort = this.selectPortById(form.getParentId());
                if (parentPort == null) {
                    throw BaseException.message("您选择的父节点不存在");
                }
            }
            // 判断要更新的节点是否存在
            BsPort bsPort = this.selectPortById(form.getId());
            if (bsPort == null) {
                throw BaseException.message("不存在您要更改的港口");
            }
            // 非根节点
            if (form.getParentId() != 0 && (parentPort.getLevel() + 1) != bsPort.getLevel()) {
                throw BaseException.message("您应该选择对应" + BasePortLevel.returnMessage(bsPort.getLevel() - 1));
            }
//            // 根节点
//            if (form.getParentId() == 0 &&  BasePortLevel.ONE_LEVEL.getLevel() != bsPort.getLevel()) {
//                throw BaseException.message("您应该选择根节点");
//            }
            // 检查港口名称是否存在
            BsPort bsPort1 = mapper.selectPortByPortNameAndLevel(form.getPortName(), bsPort.getLevel());
            if (bsPort1 != null && !bsPort1.getId().equals(form.getId())) {
                throw BaseException.message("名称:" + form.getPortName() + "已存在");
            }
            bsPort.setPortName(form.getPortName());
            bsPort.setSeqNum(form.getSeqNum());
            bsPort.setLon(form.getLon());
            bsPort.setLat(form.getLat());
            bsPort.setDisableStatus(bsPort.getDisableStatus());
            if (form.getParentId() == 0) {
                // 根节点
                bsPort.setParentId(0L);
            } else {
                // 非根节点
                bsPort.setParentId(parentPort.getId());
            }
            mapper.updateByPrimaryKeySelective(bsPort);

        }

    }

    public List<BsPort> selectPortByLeve(Integer level) {
        return mapper.selectPortByLeve(level);
    }

    public static String getEnName(String enName, Integer increase, boolean isOneLine, Integer level) {
        if (StringUtils.isEmpty(enName)) {
            return null;
        }
        if (isOneLine && level != null && BasePortLevel.THREE_LEVEL.getLevel() == level) {
            // 港口
            return enName + "00";
        } else if (isOneLine) {
            // 流域/城市
            return enName + "01";
        }
        // 编码长度
        int strLen = enName.length();
        // 转为Integer类型
        Integer value = Integer.parseInt(enName);
        // 前缀是否存在0
        int residuLen = strLen - ((Integer)Integer.parseInt(enName)).toString().length();
        // 当前值加上某个值，得到最新值
        Integer newValue = value + increase;
        StringBuffer sBuffer =  new StringBuffer();
        if (residuLen > 0 && strLen > newValue.toString().length()) {
            // 存在前缀0
            for (int i = 0 ; i < residuLen; i++) {
                sBuffer.append(0);
            }
        }
        sBuffer.append(newValue);
        return sBuffer.toString();
    }

    /**
     *
     */
    @Data
    class HasDealing {
        public  Boolean hasDealing = false;
    }
}